const Shape = require("./shape.js")
const Utils = require("./utils.js")
const {EN} = require("./constant.js")

module.exports = class Rect extends Shape{
	constructor($env,$event){
		super($env,$event)

		this.__relativePlugins=[{name:"LinePicker"}]
		this.transcation = 0
		// this.__setting = Utils.assign(this.__setting,{
		// 	r:2
		// })
		
		this.bind();
	}
	bind(){
		this.baseContext.canvas.addEventListener("click",(e)=>{
			if (!this.isActive) return;
			var pos = {
					x : e.pageX,
			        y : e.pageY
			}

			if(this.transcation===1){
				this.drawEnd(this.cvsEvtPos(pos,this.cvs));
				return;
			}
			
			this.drawStart(this.cvsEvtPos(pos,this.cvs))
		})
		this.baseContext.canvas.addEventListener("mousemove",(e)=>{
			if (!this.isActive) return;
			if(this.transcation!==1)return;
			var pos = {
					x : e.pageX,
			        y : e.pageY
			}
			this.updateBaseLine(this.cvsEvtPos(pos,this.cvs))
		})
	}
	updateBaseLine(pos){
		let rect = this.__steps[0];
		this.clearBaseContext()
		let baseContext = this.baseContext;
		baseContext.save()
		// baseContext.globalAlpha = this.$env.globalAlpha;
		this.rePaint([Utils.assign(rect,{fillStyle:this.$env.ghostFillStyle}),pos],baseContext,true)
		this.tip(rect,pos)
		baseContext.restore();
	}
	rePaint(step,context,fill){
		let ctx = context||this.ctx;
		
		let fp = step[0];
		let lp = step[step.length-1];

		ctx.strokeStyle = fp.strokeStyle
		ctx.fillStyle = fp.fillStyle

		ctx.setLineDash(fp.lineDash)
		ctx.beginPath()
		ctx.strokeRect(fp.x,fp.y,lp.x-fp.x,lp.y-fp.y);
		ctx.closePath()
		fill&&ctx.fillRect(fp.x,fp.y,lp.x-fp.x,lp.y-fp.y);

		this.drawPoint(fp,context);
		this.drawPoint(lp,context);
	}
	drawEnd(pos){
		this.clearBaseContext()
		let step = this.__steps;
		step.push(Utils.assign(this.__setting,this.rewritePos(pos)));
		
		this.rePaint(step)

		this.transcation=0;

		this.emit(EN.update_state,this,step)
		this.tipHide()
	}
	drawStart(pos){

		let p = Utils.assign(this.__setting,pos);

		let ctx = this.ctx;
		p.strokeStyle = ctx.strokeStyle
		p.fillStyle = ctx.fillStyle
		p.lineDash = ctx.getLineDash()
		p=this.rewritePos(p)

		this.drawPoint(p,this.baseContext)
		this.transcation = 1;
		this.__steps=[p];
	}
	tip(fp,lp){
		let {hr,zr} = this.rect(fp,lp,this.ratio)
		this.$event.emit("tip:show",{text:`横边长： ${hr}  纵边长：${zr}`})
	}
}
